﻿using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using In.Api.Dto.InPatientWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.Dto.Check;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class CheckController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CheckController));
        private GdsfybjyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取检验单列表
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetChecks")]
        public GetChecksResponse GetChecks(int cardId, string startDate)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCards.FirstOrDefault(x => x.CardId == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetChecksResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }

            var inpatientVisitId = "";
            var inpatientListRequest = new GetInPatientHisRequest();
            inpatientListRequest.CardNo = card.CardNo;

            //try
            //{
            //    var httpClient = InHttpClient.GetClient();
            //    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetInPatientHis", inpatientListRequest).Result;
            //    responseMsg.EnsureSuccessStatusCode();
            //    var inPatientListResponse = responseMsg.Content.ReadAsAsync<GetInPatientHisResponse>().Result;
            //    if (inPatientListResponse.ResultCode == "0")
            //    {
            //        var currentInpatient = inPatientListResponse.InPatientHisList
            //        .FirstOrDefault(x => x.IsInp == "1");
            //        if (currentInpatient != null)
            //        {
            //            inpatientVisitId = currentInpatient.VisitId;
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Logger.ErrorFormat("调用院内获取住院记录Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
            //}

            if (string.IsNullOrEmpty(inpatientVisitId))
            {
                var request = new GetExamInfoRequest();
                request.CardNo = card.CardNo;
                request.ItemType = "2";
                request.BeginDate = startDate.ToDateTimeOrDefault().ToString("yyyy-MM-dd");
                request.EndDate = startDate.ToDateTimeOrDefault().AddDays(15).ToString("yyyy-MM-dd");

                GetExamInfoResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetExamInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetExamInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取检验单列表Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetChecksResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检验单列表超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetChecksResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetChecksResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    IsInp = "0",
                    Checks = response.ExamList.OrderBy(x => x.Status)
                        .ThenByDescending(x => x.ExamID)
                        .Select(x => new GetChecksResponse.Check
                        {
                            Id = x.ExamID,
                            Name = x.ExamName,
                            Date = x.ExamDate,
                            //CardNo = x.CardNo,
                            PatientName = x.PatientName,
                            PatientSex = x.PatientSex,
                            Status = x.Status
                        }).ToList()
                };
            }
            else
            {
                var request = new InpGetExamInfoRequest();
                request.PatientId = card.CardNo;
                request.ItemType = "D";
                request.VisitId = inpatientVisitId;

                InpGetExamInfoResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("InpatientWs/InpGetExamInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<InpGetExamInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取住院检验单列表Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetChecksResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检验单列表超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetChecksResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetChecksResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    IsInp = "1",
                    Checks = response.ExamList.OrderBy(x => x.Status)
                        .ThenByDescending(x => x.ExamId)
                        .Select(x => new GetChecksResponse.Check
                        {
                            Id = x.ExamId,
                            Name = x.ExamName,
                            Date = x.ExamDate,
                           // CardNo = x.CardNo,
                            PatientName = x.PatientName,
                            PatientSex = x.PatientSex,
                            Status = x.Status
                        }).ToList()
                };
            }
        }

        /// <summary>
        /// 获取检验单详情
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="appNo"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetCheckDetail")]
        public GetCheckDetailResponse GetCheckDetail(int cardId, string appNo)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCards.FirstOrDefault(x => x.CardId == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetCheckDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }

            var inpatientVisitId = "";
            var inpatientListRequest = new GetInPatientHisRequest();
            inpatientListRequest.CardNo = card.CardNo;

            //try
            //{
            //    var httpClient = InHttpClient.GetClient();
            //    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetInPatientHis", inpatientListRequest).Result;
            //    responseMsg.EnsureSuccessStatusCode();
            //    var inPatientListResponse = responseMsg.Content.ReadAsAsync<GetInPatientHisResponse>().Result;
            //    if (inPatientListResponse.ResultCode == "0")
            //    {
            //        var currentInpatient = inPatientListResponse.InPatientHisList
            //        .FirstOrDefault(x => x.IsInp == "1");
            //        if (currentInpatient != null)
            //        {
            //            inpatientVisitId = currentInpatient.VisitId;
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Logger.ErrorFormat("调用院内获取住院记录Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
            //}

            if (string.IsNullOrEmpty(inpatientVisitId))
            {
                var request = new GetExamDetailRequest();
                request.CardNo = card.CardNo;
                request.ExamId = appNo;
                request.ItemType = "D";

                GetExamDetailResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetExamDetail", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetExamDetailResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取检验单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetCheckDetailResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检验单详情超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetCheckDetailResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetCheckDetailResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    CheckItems = response.ExamItemList.Select(x => new GetCheckDetailResponse.CheckItem
                    {
                        ItemNo = x.ItemNo,
                        ItemDate = x.ItemDate,
                        LabRepItemName = x.LabItemName,
                        LabRepUnits = x.LabRepUnits,
                        LabInd = x.LabInd,
                        LabContext = x.LabContext,
                        LabRepResult = x.LabRepResult,
                    }).ToList()
                };
            }
            else
            {
                var request = new InpGetExamDetailRequest();
                request.ExamId = appNo;
                request.ItemType = "D";

                InpGetExamDetailResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("InpatientWs/InpGetExamDetail", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<InpGetExamDetailResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取住院检查单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetCheckDetailResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检查单详情超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetCheckDetailResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetCheckDetailResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    CheckItems = response.ExamItemList.Select(x => new GetCheckDetailResponse.CheckItem
                    {
                        ItemNo = x.ItemNo,
                        ItemDate = x.ItemDate,
                        Prompt = x.ExamPrompt,
                        Content = x.ExamContent
                    }).ToList()
                };
            }
        }
    }
}
